package com.erp.erp_ui.BillExchangeInfo;

import com.alibaba.fastjson.JSONObject;
import com.erp.enums.ModuleTypeEnum;
import com.erp.enums.OperationStatusEnum;
import com.erp.erp_entitys.BillExchangeInfo.*;
import com.erp.erp_entitys.ProductMainInfo.ProductMainInfoEntity;
import com.erp.erp_entitys.ProductMainInfo.ProductMainInfoExample;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.bill_declare.BillDeclareInfo;
import com.erp.erp_entitys.bill_declare.InfoSearch;
import com.erp.erp_entitys.bill_declare.carryInfoSearch;
import com.erp.erp_entitys.bill_declare.logo;
import com.erp.erp_entitys.business.entity.CarryDetailCostEntity;
import com.erp.erp_entitys.business.entity.CarryDetailEntity;
import com.erp.erp_entitys.business.entity.CarryDetailProductEntity;
import com.erp.erp_entitys.business.entity.CarryDetailProductPartsEntity;
import com.erp.erp_entitys.business.req.ContractStatisticsOneReq;
import com.erp.erp_entitys.money.entity.ReceivePaymentDetailEntity;
import com.erp.erp_entitys.money.entity.ReceivePaymentSplitEntity;
import com.erp.erp_entitys.warehouse.entity.AnnexEntity;
import com.erp.erp_servers.Company.ICompanyService;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.ProductMainInfo.IProductMainInfoService;
import com.erp.erp_servers.User.IUserService;
import com.erp.erp_servers.bill_declare.BillDeclareInfoService;
import com.erp.erp_servers.bill_exchange.*;
import com.erp.erp_servers.business.ICarryDetailCostService;
import com.erp.erp_servers.business.ICarryDetailProductPartsService;
import com.erp.erp_servers.business.ICarryDetailProductService;
import com.erp.erp_servers.business.ICarryDetailService;
import com.erp.erp_servers.money.IReceivePaymentDetailService;
import com.erp.erp_servers.money.IReceivePaymentSplitService;
import com.erp.erp_servers.warehouse.IAnnexService;
import com.erp.erp_servers.warehouse.ITempAnnexService;
import com.erp.erp_ui.base.Base;
import com.erp.erp_ui.business.controller.ExportContractController;
import com.erp.erp_ui.email.EmailUnit;
import com.erp.erp_ui.warehouse.enums.DataIsValidEnum;
import com.erp.erp_ui.warehouse.req.AnnexReq;
import com.erp.erp_ui.warehouse.vo.AnnexVo;
import com.erp.utils.BeanChangeLogUtil;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.erp.vo.SelectVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 报关主信息表(BillDeclareInfo)表控制层
 *
 * @author makejava
 * @since 2021-01-08 17:44:10
 */
@Controller
@RequestMapping("billChange")
public class BillExchangeProductInfoController extends Base {
    /**
     * 服务对象
     */
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private  BillExchangeCostInfoService costService;
    @Autowired
    private  BillExchangeFileService fileService;
    @Autowired
    private BillExchangeInfoService infoService;
    @Autowired
    private BillExchangeLogService logService;
    @Autowired
    private  BillExchangeProductInfoService productService;
    @Autowired
    private  BillExchangeProductPartsService partService;
    @Autowired
    private ICarryDetailService carryService;
    @Autowired
    private ICarryDetailCostService carryDetailCostService;
    @Autowired
    private ICarryDetailProductService produceService;
    @Autowired
    private  IProductMainInfoService productMainInfoService;
    @Autowired
    private  ICarryDetailProductPartsService partsService;
    @Autowired
    private BillDeclareInfoService billDeclareInfoService;
    @Autowired
    private IFtpService ftpService;
    @Autowired
    private ITempAnnexService tempAnnexService;
    /**
     * 附件接口
     */
    @Autowired
    private  IAnnexService annexService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IReceivePaymentDetailService receivePaymentDetailService;
    @Autowired
    private IReceivePaymentSplitService receivePaymentSplitService;
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ExportContractController.class);
    /*
     * 分页查询所有的结汇表
     * */
    @GetMapping(value = "selectAllchangeByPage")
    @ResponseBody
    public R<List<BillExchangeInfo>> selectAllBill(InfoSearch search) {
        UserEntity user = (UserEntity) this.getBean("user");
        if(search.getDeptOperationCode()==null && search.getDeptSalesmanCode()==null &&search.getStatus()==null&&search.getSalesman_code()==null&&search.getOp_code()==null&&search.getInvoiceStar()==null&&search.getInvoiceEnd()==null&&search.getCompany_code()==null&&search.getCarryStar()==null&&search.getCarryEnd()==null&&search.getBill()==null){
            search.setOp_code(user.getCode());
        }
        if(search.getOperationCode()==null){
            search.setOperationCode(new ArrayList<>());
        }
        if(search.getSalesmanCode()==null){
            search.setSalesmanCode(new ArrayList<>());
        }
        if(StringUtils.isEmpty(search.getDeptOperationCode()) && StringUtils.isEmpty(search.getDeptSalesmanCode()) && search.getOperationCode().size()==0&&search.getSalesmanCode().size()==0){
            search.setDeptOperationCode(user.getCode());

            List<String> operationCode = new ArrayList<>();
            operationCode.add(user.getCode());
            search.setOperationCode(operationCode);

        }
        search = ChangeUnit.getSearch(search);
        List<BillExchangeInfo> infos = infoService.selectAllInfobySearch(search);
        return  R.build(infos);
    }
    /*
     * 统计费用
     * */
    @GetMapping(value = "selectCostByPage")
    @ResponseBody
    public R<List<Cost>> selectCostByPage(InfoSearch search) {
        search=getSearch(search);
        List<Cost> infos = infoService.selectCostbySearch(search);
        for(Cost c:infos){
            try {
           if(c.getMoney_kind().equals("人民币")){
               BigDecimal divide = null;
               if(c.getUsd_rate().compareTo(BigDecimal.valueOf(1)) == 1){
                   divide= c.getCost_money().divide(c.getUsd_rate(), 2, BigDecimal.ROUND_HALF_UP);
               }else{
                   divide=c.getCost_money().multiply(c.getUsd_rate()).divide(BigDecimal.valueOf(1), 2, BigDecimal.ROUND_HALF_UP);
               }
               c.setUsb(divide);
               c.setRmb(c.getCost_money());
           }else{
               //  return (element.cost_money*element.usd_rate).toFixed(2);
               BigDecimal multiply = (c.getCost_money().multiply(c.getUsd_rate())).divide(BigDecimal.valueOf(1),2,BigDecimal.ROUND_HALF_UP);
               c.setUsb(multiply);
               BigDecimal divide = c.getCost_money().multiply(c.getUsd_rate()).multiply(c.getRmb_rate()).divide(BigDecimal.valueOf(1), 2, BigDecimal.ROUND_HALF_UP);
               c.setRmb(divide);
           }
        }catch (Exception e){

            }
        }
        return  R.build(infos);
    }

    /*
     * 统计产品
     * */
    @GetMapping(value = "selectProductStaticByPage")
    @ResponseBody
    public R<List<Product>> selectProductStaticByPage(InfoSearch search) {
        search=getSearch(search);
        List<Product> infos = infoService.selectProductStaticbySearch(search);
        for(Product p:infos){
            try{
            if(p.getMoneyKind().equals("人民币")){
                BigDecimal divide = null;
                if(p.getUsd_rate().compareTo(BigDecimal.valueOf(1)) == 1){
                    divide= p.getFtotalprice().divide(p.getUsd_rate(), 2, BigDecimal.ROUND_HALF_UP);
                }else{
                    divide=p.getFtotalprice().multiply(p.getUsd_rate()).divide(BigDecimal.valueOf(1), 2, BigDecimal.ROUND_HALF_UP);
                }
                p.setUsb(divide);
                p.setRmb(p.getFtotalprice());
            }else{
                BigDecimal divide = p.getFtotalprice().multiply(p.getUsd_rate()).divide(BigDecimal.valueOf(1), 2, BigDecimal.ROUND_HALF_UP);
                p.setUsb(divide);
                BigDecimal divide1 = p.getFtotalprice().multiply(p.getUsd_rate()).multiply(p.getRmb_rate()).divide(BigDecimal.valueOf(1), 2, BigDecimal.ROUND_HALF_UP);
                p.setRmb(divide1);
            }}catch (Exception e){

            }
        }

        return  R.build(infos);
    }
    @GetMapping(value = "selectAllUser")
    @ResponseBody
    public R<List<UserEntity>> selectAllUser() {
        List<UserEntity> user = userService.getAllUserNameAndCode();
        return  R.build(user);
    }
    /*
     * 修改报关表状态
     *(1.草稿箱 2.待批箱 3.已批箱 4.完成箱 5.垃圾箱)
     * */
    @GetMapping(value = "changeBillById")
    @ResponseBody
    public R<String> changeBillById(Integer billId, Integer statues) {
        String succ="success";
        try{
            BillExchangeInfo info = infoService.queryById(billId);
            info.setStatus(statues);
            infoService.update(info);
        }catch (Exception e){
            succ="wrong";
        }
        return R.build(succ);
    }

    /*
     * 查询所有的签约公司、操作员和业务员
     * */
    @GetMapping(value = "selectAllcompanyAndpeople")
    @ResponseBody
    public R<Map<String, List>> selectAllcompanyAndpeople(Integer Type) {
        //查询所有的签约公司
        List<SelectVo> list = companyService.getAllList();
        Map<String,List> map=new HashMap<>();
        map.put("companyName",list);
        return R.build(map);

    }
    /*
     * 分页查询出运明细
     * */
    @GetMapping(value = "selectAllCarryByPage")
    @ResponseBody
    public R<List<CarryDetailEntity>> selectAllCarryByPage(carryInfoSearch search) {
        UserEntity user = (UserEntity) this.getBean("user");
        List<CarryDetailEntity> infos=new ArrayList<>();
        try {
            search = ChangeUnit.getSearch(search);
            if(search.getSalesmanCode().size()==0){
                List<String> code=new ArrayList<>();
                code.add(user.getCode());
                search.setSalesmanCode(code);
                search.setIsNull(1);
            }else{
                search.setIsNull(1);
            }
            infos = infoService.queryCarryBySearchExchange(search);
        }catch (Exception e){
            System.out.println(e);
        }
        for(CarryDetailEntity ca:infos){
            ca.setOperator(user.getName());
        }
        return  R.build(infos);
//        UserEntity user = (UserEntity) this.getBean("user");
//        search = ChangeUnit.getSearch(search);
//        List<CarryDetailEntity> infos=new ArrayList<>();
//        try {
//            if(search.getNumberremaining()==null&&search.getMdate()==null&&search.getInvoiceno()==null&&search.getEndmdate()==null&&search.getCustomername()==null&&search.getCustomercontractno()==null&&search.getContractno()==null){
//                search.setIsNull(0);
//            }else{
//                search.setIsNull(1);
//            }
//            infos = billDeclareInfoService.queryCarryBySearch(search);
//        }catch (Exception e){
//
//        }
//
//        for(CarryDetailEntity ca:infos){
//            ca.setOperator(user.getName());
//        }
//        return  R.build(infos);
    }

    /*
     * 将出运产品转换为结汇产品
     * */
    @PostMapping(value="changeProducts")
    @ResponseBody
    public R<List<BillExchangeProductInfo>> changeProductsAndParts(@RequestBody List<CarryDetailProductEntity> pro){
        List<BillExchangeProductInfo> billPro=new ArrayList<>();
        if(pro.size()>0){
            for(CarryDetailProductEntity p:pro){
                BillExchangeProductInfo productInfo = new BillExchangeProductInfo(p);
                BigDecimal bigDecimal = productService.selectLastAmount(productInfo);
                BigDecimal last=productInfo.getGoodsNum().subtract(bigDecimal);
                if(last.compareTo(new BigDecimal(0))>0){
                    productInfo.setLastAmount(last);
                    p.setCostSubtotal(p.getCostUnitPrice().multiply(last));
                    p.setMoneySubtotal(p.getFcUnitPrice().multiply(last));
                    billPro.add(productInfo);
                }
            }
        }
        return R.build(billPro);
    }
    /*
     * 分页查询出运产品
     *
     * */
    @GetMapping(value = "selectCarryProductByPage")
    @ResponseBody
    public R<List<CarryDetailProductEntity>> selectCarryProductByPage(Integer id) {
        List<CarryDetailProductEntity> infos = billDeclareInfoService.queryCarryProductByCarryId(id);
        List<CarryDetailProductEntity> products=new ArrayList<>();
        for(CarryDetailProductEntity pro :infos){
            BillExchangeProductInfo info = new BillExchangeProductInfo(pro);
            BigDecimal bigDecimal = productService.selectLastAmount(info);
            BigDecimal last=info.getGoodsNum().subtract(bigDecimal);
            if(last.compareTo(new BigDecimal(0))>0){
                pro.setLastAmount(last);
                pro.setCostSubtotal(pro.getCostUnitPrice().multiply(last));
                pro.setMoneySubtotal(pro.getFcUnitPrice().multiply(last));
                products.add(pro);
            }
        }
        return  R.build(products);
    }
    /*
     * 分页查询出运配件
     *
     * */
    @GetMapping(value = "selectAllPart")
    @ResponseBody
    public R<List<BillExchangeProductParts>> selectPartByPage(@RequestParam(value = "carryid") Integer carryid, @RequestParam(value = "carryproid") Integer carryproid) {
        CarryDetailProductPartsEntity carry=new CarryDetailProductPartsEntity();
        carry.setCarryDetailId(carryid);
        carry.setProductDetailId(carryproid);
        List<CarryDetailProductPartsEntity> infos =partsService.queryAll(carry);
        List<BillExchangeProductParts> products=new ArrayList<>();
        for(CarryDetailProductPartsEntity pro :infos){
            BillExchangeProductParts info = new BillExchangeProductParts(pro);
            BigDecimal bigDecimal = partService.selectLastAmount(info);
            BigDecimal last=info.getGoodsnumParts().subtract(bigDecimal);
            if(last.compareTo(new BigDecimal(0))>0){
                info.setLastAmount(last);
                pro.setCostSubtotal(pro.getCostUnitPrice().multiply(last));
                products.add(info);
            }
        }
        return  R.build(products);
    }
    /*
     * 查询最大可报关数量
     * */
    @GetMapping(value = "selectLastAmontById")
    @ResponseBody
    public R<BigDecimal> selectLastAmontById(@RequestParam(value = "proid") Integer proid, @RequestParam(value = "type") Integer type) {//type=1 是产品，2是附件
        if(type==1){
            BillExchangeProductInfo info = new BillExchangeProductInfo();
            info.setCarryProductsId(proid);
            BigDecimal productNum = produceService.queryById(proid).getProductNum();
            BigDecimal bigDecimal = productService.selectLastAmount(info);
            BigDecimal lastDecimal=productNum.subtract(bigDecimal);
            return R.build(lastDecimal);
        }else{
            BillExchangeProductParts info =new BillExchangeProductParts();
            info.setCarryPartsId(proid);
            BigDecimal amount = partsService.queryById(proid).getPartsAmount();
            BigDecimal bigDecimal =partService.selectLastAmount(info);
            BigDecimal lastDecimal=amount.subtract(bigDecimal);
            return R.build(lastDecimal);
        }

    }

    /*
    * insertBillChangeInfo
    * 新建或者修改billChangeInfo数据
    * type=1，新增   type=2，修改
    * */
    @PostMapping(value = "insertBillChangeInfo")
    @ResponseBody
    public R<Integer> insertBillChangeInfo(@RequestBody BillExchangeInfo info, @RequestParam(value = "type")Integer type){
        UserEntity user = (UserEntity)this.getBean("user");
            if(type==1){
                //校验单号是否重复
                List<BillExchangeInfo> billExchangeInfos = infoService.checkBillNo(info.getInvoiceNo());
                boolean billNoFlag = CollectionUtils.isEmpty(billExchangeInfos) || billExchangeInfos.get(0).getStatus() == OperationStatusEnum.TRASH_CAN.getId();
                if(!billNoFlag){
                    return R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
                }
                info.setCreateTime(new Date());
                info.setEditTime(new Date());
                info.setStatus(1);
                infoService.insert(info);
                BillExchangeLog log=new BillExchangeLog();
                log.setOptioner(user.getName()+"("+user.getCode()+")");
                log.setOptionTime(EmailUnit.getNowSqlDate());
                log.setInvoiceNo(info.getBillId()+"");
                log.setType("新增");
                logService.insert(log);
                return R.build(info.getBillId());
            }else {
                BillExchangeInfo info1 = infoService.queryById(info.getBillId());
                info.setTotalTariffAmount(info.getTotalTariffAmount());
                info.setInvoiceMoney(info.getInvoiceMoney());
                BillExchangeLog log=new BillExchangeLog();
                log.setOptioner(user.getName()+"("+user.getCode()+")");
                log.setOptionTime(EmailUnit.getNowSqlDate());
                log.setInvoiceNo(info.getBillId()+"");
                log.setType("结汇表修改");
                BeanChangeLogUtil<BillExchangeInfo> t = new BeanChangeLogUtil<>();
                String str = t.contrastObj(info, info1);
                if (str.equals("")) {
                    str="主表未有改变";
                }else{
                    log.setContent(str);
                    logService.insert(log);
                }
                info.setEditTime(new Date());
                infoService.update(info);
                return R.build(info.getBillId());
            }
    }

    /*
     * insertBillChangeProductInfo
     * 新建或者修改billChangeProductInfo数据
     * type=1，新增   type=2，修改
     * */
    @PostMapping(value = "insertBillChangeProductInfo")
    @ResponseBody
    public R<Integer> insertBillChangeProductInfo(@RequestBody BillExchangeProductInfo info, @RequestParam(value = "type")Integer type, @RequestParam(value = "billId")Integer billId){
        UserEntity user = (UserEntity)this.getBean("user");
        if(type==1){
            info.setBillId(billId);
            productService.insert(info);
            return R.build(info.getBillProductId());
        }else {
            productService.update(info);
            return R.build(info.getBillProductId());
        }
    }

    /*
     * insertBillChangePartInfo
     * 新建或者修改billChangepartInfo数据
     * type=1，新增   type=2，修改
     * */
    @PostMapping(value = "insertBillChangePartInfo")
    @ResponseBody
    public void insertBillChangePartInfo(@RequestBody List<BillExchangeProductParts> infos, @RequestParam(value = "type")Integer type, @RequestParam(value = "billId")Integer billId, @RequestParam(value = "productid")Integer productid){
        if(type==1&&infos.size()>0){
          for(BillExchangeProductParts part:infos){
                part.setBillId(billId);
                part.setBillProductId(productid);
                partService.insert(part);
          }
        }else if(type!=1&&infos.size()>0){
            for(BillExchangeProductParts part:infos){
                partService.update(part);
            }
        }
    }

    /*
     * 根据id删除结汇表和产品表配件表
     * deleteBillById
     * */
    @GetMapping(value = "deleteBillById")
    @ResponseBody
    public R<String> deleteBillById(Integer billId) {
        String succ="success";
        try{
            //删除结汇表
            infoService.deleteById(billId);
            //删除产品表
            BillExchangeProductInfo productInfo = new BillExchangeProductInfo();
            productInfo.setBillId(billId);
            List<BillExchangeProductInfo> productInfos = productService.queryAll(productInfo);
            List<BillExchangeProductParts> parts=new ArrayList<>();
            if(productInfos.size()>0){
                for(BillExchangeProductInfo pro:productInfos){
                    productService.deleteById(pro.getBillProductId());
                    //将需要删除的配件加入删除集合
                    BillExchangeProductParts p=new BillExchangeProductParts();
                    p.setBillId(billId);
                    p.setBillProductId(pro.getBillProductId());
                    List<BillExchangeProductParts> parts1 = partService.queryAllByLimit(p);
                    if(parts1.size()>0){
                        parts.addAll(parts1);
                    }
                }
                //删除配件
                if(parts.size()>0){
                    for(BillExchangeProductParts p:parts){
                        partService.deleteById(p.getId());
                    }
                }
            }
        }catch (Exception e){
            succ="wrong";
        }
        return R.build(succ);
    }

    /*
     * 根据id删除结汇表和产品表配件表
     * deleteBillById
     * */
    @GetMapping(value = "selectInfoBillById")
    @ResponseBody
    public R<Map<String,List>> selectInfoBillById(@RequestParam(value = "billId") Integer billId) {
        //查询到的主表信息
        BillExchangeInfo info = infoService.queryById(billId);
        List<BillExchangeInfo> bill=new ArrayList<>();
        bill.add(info);
        //查询到的产品信息
        BillExchangeProductInfo pro=new BillExchangeProductInfo();
        pro.setBillId(billId);
        List<BillExchangeProductInfo> productInfos = productService.queryAll(pro);
        //查询配件信息
        BillExchangeProductParts part=new BillExchangeProductParts();
        part.setBillId(billId);
        List<BillExchangeProductParts> parts = partService.queryAllByLimit(part);
        //查询费用
        BillExchangeCostInfo cost=new BillExchangeCostInfo();
        cost.setParentId(billId);
        List<BillExchangeCostInfo> costInfos = costService.queryAll(cost);
        //返回前端
        Map<String,List> map=new HashMap<>();
        map.put("bill",bill);
        map.put("products",productInfos);
        map.put("parts",parts);
        map.put("costs",costInfos);
        return R.build(map);
    }



    /*
     * 根据结汇配件id查询改配件属于哪个出运产品id
     *  selectcarryProductsIdByPartId
     * */
    @GetMapping(value = "selectcarryProductsIdByPartId")
    @ResponseBody
    public R<Integer> selectcarryProductsIdByPartId(@RequestParam(value = "partId") Integer partId) {
        BillExchangeProductParts parts = partService.queryById(partId);
        BillExchangeProductInfo productInfo = productService.queryById(parts.getBillProductId());
        return R.build(productInfo.getCarryProductsId());
    }

    /*
    * 修改结汇产品表
    * updateBillChangeProductInfo
    * */
    @PostMapping(value = "updateBillChangeProductInfo")
    @ResponseBody
    public void updateBillChangeProductInfo(@RequestBody List<BillExchangeProductInfo> pros, @RequestParam(value = "billid") Integer billid) {
        BillExchangeProductInfo p=new BillExchangeProductInfo();
        UserEntity user = (UserEntity)this.getBean("user");
        p.setBillId(billid);
        List<BillExchangeProductInfo> infos = productService.queryAll(p);//原数据
        List<BillExchangeProductInfo> delete=new ArrayList<>();//需要删除的表
        if(infos.size()!=pros.size()){//存在删除情况
            for(BillExchangeProductInfo old:infos){
                 int i=0;//0是不重复，1是重复
                for(BillExchangeProductInfo now:pros){
                    if(old.getBillProductId().equals(now.getBillProductId())){//原数据中有新表数据
                        i=1;
                    }
                }
                if(i==0){
                    delete.add(old);
                }
            }
        }
        String str="";
        BillExchangeLog log=new BillExchangeLog();
        log.setOptioner(user.getName()+"("+user.getCode()+")");
        log.setOptionTime(EmailUnit.getNowSqlDate());
        log.setInvoiceNo(billid+"");
        log.setType("产品修改");
        if(pros.size()>0){
        for(BillExchangeProductInfo now:pros){
            BillExchangeProductInfo info1 = productService.queryById(now.getBillProductId());
            BeanChangeLogUtil<BillExchangeProductInfo> t = new BeanChangeLogUtil<>();
            String st= t.contrastObj(now, info1);
            if (st.equals("")) {
                st="产品未有未有改变";
            }else{
                str+="产品编码"+now.getGoodsCode()+"产品:"+st+";";
            }
            productService.update(now);
        }}
        if(delete.size()>0){
            for(BillExchangeProductInfo de:delete){
                str+="产品编码"+de.getGoodsCode()+"产品被删除";
                productService.deleteById(de.getBillProductId());
            }
        }
      if(str.equals("")==false){
          log.setContent(str);
          logService.insert(log);
      }

    }
    /*
     * 修改结汇配件表
     * updateBillChangePartInfo
     * */
    @PostMapping(value = "updateBillChangePartInfo")
    @ResponseBody
    public void updateBillChangePartInfo(@RequestBody List<BillExchangeProductParts> parts, @RequestParam(value = "billid") Integer billid) {
        BillExchangeProductParts p=new BillExchangeProductParts();
        p.setBillId(billid);
        List<BillExchangeProductParts> parts1 = partService.queryAllByLimit(p);//原数据
        List<BillExchangeProductParts> delete=new ArrayList<>();//需要删除的数据
        if(parts1.size()!=parts.size()){//存在删除情况
            for(BillExchangeProductParts old:parts1){
                int i=0;//0是不重复，1是重复
                for(BillExchangeProductParts now:parts){
                    if(old.getId()==now.getId()){//原数据中有新表数据
                        i=1;
                    }
                }
                if(i==0){
                    delete.add(old);
                }
            }
        }
        if(parts.size()>0){
            for(BillExchangeProductParts now:parts){
               partService.update(now);
            }}
        if(delete.size()>0){
            for(BillExchangeProductParts de:delete){
                partService.deleteById(de.getId());
            }
        }
    }

    /*
    * newCost
    * 查询出运费用信息
    * */
    @PostMapping(value = "selectCost")
    @ResponseBody
    public R<List<CarryDetailCostEntity>> selectCost(@RequestBody List<CarryDetailEntity> carryids) {
        List<CarryDetailCostEntity> costEntities=new ArrayList<>();
        for(CarryDetailEntity i:carryids){
            CarryDetailCostEntity costEntity=new CarryDetailCostEntity();
            costEntity.setParentId(i.getId());
            List<CarryDetailCostEntity> cost= carryDetailCostService.queryAll(costEntity);
            costEntities.addAll(cost);
        }
            return R.build(costEntities);
    }

    /*
    * insertBillChangeCost
    * 新增费用  type=1 新增  =2  修改
    * */
    @PostMapping(value = "insertBillChangeCost")
    @ResponseBody
    public void insertBillChangeCost(@RequestBody List<CarryDetailCostEntity> costs, @RequestParam(value = "type") Integer type, @RequestParam(value = "billId") Integer billId) {
        if(type==1){
            List<BillExchangeCostInfo> billCosts=new ArrayList<>();
            for(CarryDetailCostEntity c:costs){
                BillExchangeCostInfo cos=new BillExchangeCostInfo(c);
                cos.setParentId(billId);
                billCosts.add(cos);
            }
            for(BillExchangeCostInfo bc:billCosts){
                costService.insert(bc);
            }
        }
        if(type==2){
            //简单做法，删除原有的，新增新的
            BillExchangeCostInfo cost=new BillExchangeCostInfo();
            cost.setParentId(billId);
            List<BillExchangeCostInfo> billExchangeCostInfos = costService.queryAll(cost);
            for(BillExchangeCostInfo de:billExchangeCostInfos){
                costService.deleteById(de.getId());
            }
            //新增
            List<BillExchangeCostInfo> billCosts=new ArrayList<>();
            for(CarryDetailCostEntity c:costs){
                BillExchangeCostInfo cos=new BillExchangeCostInfo(c);
                cos.setParentId(billId);
                billCosts.add(cos);
            }
            for(BillExchangeCostInfo bc:billCosts){
                costService.insert(bc);
            }


        }

    }
    /*
     * insertBillChangeCost
     * 新增费用  type=1 新增  =2  修改
     * */
    @PostMapping(value = "insertBillChangeCost1")
    @ResponseBody
    public void insertBillChangeCost1(@RequestBody List<BillExchangeCostInfo> costs, @RequestParam(value = "type") Integer type, @RequestParam(value = "billId") Integer billId) {
        UserEntity user = (UserEntity)this.getBean("user");
        if(type==2){
            //简单做法，删除原有的，新增新的
            BillExchangeCostInfo cost=new BillExchangeCostInfo();
            cost.setParentId(billId);
            List<BillExchangeCostInfo> billExchangeCostInfos = costService.queryAll(cost);
            String oldstr="";//原费用:
            String newstr="";//新费用:
            for(BillExchangeCostInfo de:billExchangeCostInfos){
                costService.deleteById(de.getId());
                oldstr+=de.getContractNo()+","+de.getCostDesc()+","+de.getCostMoney();

            }
            //新增
            for(BillExchangeCostInfo c:costs){
                c.setParentId(billId);
                newstr+=c.getContractNo()+","+c.getCostDesc()+","+c.getCostMoney();
                costService.insert(c);
            }
            if(oldstr.equals(newstr)==false){
                BillExchangeLog log=new BillExchangeLog();
                log.setOptioner(user.getName()+"("+user.getCode()+")");
                log.setOptionTime(EmailUnit.getNowSqlDate());
                log.setInvoiceNo(billId+"");
                log.setType("费用变更");
                log.setContent("原费用:"+oldstr+"。新费用:"+newstr);
                logService.insert(log);
                }
            }

        }


    /*
     * 根据产品编码和规格编码获取海关编码
     * */
    @GetMapping(value = "selectTariffRate")
    @ResponseBody
    public R<String> selectTariffRate(@RequestParam(value = "goodsCode") String goodsCode,@RequestParam(value = "specCode") String specCode){
        ProductMainInfoExample p=new  ProductMainInfoExample();
        ProductMainInfoExample.Criteria criteria = p.createCriteria();
        criteria.andCodeEqualTo(goodsCode);
        List<ProductMainInfoEntity> infoEntities = productMainInfoService.selectByExample(p);
        return R.build(infoEntities.get(0).getHgCode());
    }

    /**
     * FTP文件上传
     * @param request
     * @return
     */
    @RequestMapping(value = "uploadFile" ,method = RequestMethod.POST, consumes = "multipart/*")
    @ResponseBody
    public R transferFileUpload(MultipartHttpServletRequest request){
        try {
            String ftpPath = getFtpPath();
            UserEntity user = (UserEntity)this.getBean("user");
            String operator = user.getName();
            String operatorNo = user.getCode();
            List<AnnexVo> annexVos =ChangeUnit.transferFileUpload(tempAnnexService,ftpService,request, ftpPath, operator, operatorNo);
            return R.build(annexVos);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.UPLOAD_FILE_ERROR);
        }
    }
    /**
     * 新增、修改
     * @param req 新增、修改入参
     * @return 新增、修改结果
     */
    @PostMapping("/add")
    @ResponseBody
    public R add(@RequestBody List<AnnexReq> req, @RequestParam(value = "id") Integer id, @RequestParam(value = "type") Integer type){//type==-1  新增 type!=-1 修改
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            String name = user.getName();
            String code = user.getCode();
            if(type==-1){
                return ChangeUnit.add(tempAnnexService,annexService,req,name, id,code);
            } else{
                annexService.deleteAnnex(ModuleTypeEnum.BILLCHANGE_FILE.getId(),id);
                return ChangeUnit.add(tempAnnexService,annexService,req,name, id,code);
            }

        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 新增、修改
     * @param req 新增、修改入参
     * @return 新增、修改结果
     */
    @PostMapping("/addNew")
    @ResponseBody
    public R addNew(@RequestBody List<AnnexReq> req, @RequestParam(value = "id") Integer id, @RequestParam(value = "type") Integer type){//type==-1  新增 type!=-1 修改
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            String name = user.getName();
            String code = user.getCode();
            annexService.deleteAnnex(ModuleTypeEnum.BILLCHANGE_FILE.getId(),id);
            return ChangeUnit.add(tempAnnexService,annexService,req,name, id,code);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * ftp路径，/upload/部门编码/员工编码
     * @return
     */
    private String getFtpPath(){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            String code = user.getCode();
            String departmentCode = user.getDepartmentCode();
            return "/data0/AllPath/upload/"+departmentCode+"/"+code;
        }catch (Exception e){
            e.printStackTrace();
            return "/data0/AllPath/upload";
        }

    }

    /*
     * 根据表id查询附件
     * */
    //获取对应所有附件
    @GetMapping("/selectBillFile")
    @ResponseBody
    public R<List<AnnexVo>> add(Integer type,Integer parentId){
        Integer moduleId=-1;
        if(type==0){//查询出运
            moduleId=ModuleTypeEnum.BUSINESS_CARRY_DETAIL.getId();
        }else if(type==1){//查询报关
            moduleId=ModuleTypeEnum.BILLDECLARE_FILE.getId();
        }else if(type==2){//查询结汇
            moduleId=ModuleTypeEnum.BILLCHANGE_FILE.getId();
        }else if(type==3){//查询清关
            moduleId=ModuleTypeEnum.BILLCLEAR_FILE.getId();
        }
        AnnexEntity annex = new AnnexEntity();
        annex.setModuleId(moduleId);
        annex.setParentId(parentId);
        annex.setValid(DataIsValidEnum.VALID.getId());
        List<AnnexEntity> annexList = annexService.queryAll(annex);
        List<AnnexVo>  anvoList=new ArrayList<>();
        for(AnnexEntity a:annexList){
            AnnexVo v=new AnnexVo();
            v.setId(a.getId());
            v.setUploadTime(DateUtils.format(a.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
            v.setFileName(a.getFileName());
            v.setFilePath(a.getFilePath());
            anvoList.add(v);
        }
        return R.build(anvoList);
    }

    /*
     * 查询是否管理员
     * */
    @GetMapping("/isMsn")
    @ResponseBody
    public R<String> isMsn(){
        UserEntity user = (UserEntity) this.getBean("user");
        return R.build(user.getMsn());
    }

    /*
     * 根据出运编计划号查询备货日期
     * */
    @GetMapping("/selectpickupdate")
    @ResponseBody
    public R<String> selectpickupdate(String billNo){
        String da=billDeclareInfoService.selectpickupdate(billNo);//2021-03-24 00:00:00
        try{
            da=da.substring(0,10);
        }catch (Exception e ){

        }
        return R.build(da);
    }
    /*
     * 根据出运编计划号查询备货日期
     * */
    @GetMapping("/selectBillExchangeLogsByPage")
    @ResponseBody
    public R<List<BillExchangeLog>> selectBillExchangeLogs(String billNo){
        List<BillExchangeLog> exchangeLogs=new ArrayList<>();
        try{
            if (billNo!=null&&billNo.equals("")==false){
                exchangeLogs= logService.queryByBillId(billNo);
            }
        }catch (Exception e){}
        return R.build(exchangeLogs);
    }

    /*
     * 验证单号是否唯一
     * */
    @GetMapping("/checkBillNo")
    @ResponseBody
    public R<String> checkBillNo(String  invoicenumber,Integer id){
        if(id==null){
            id=-1;
        }
        String re="success";
        try {
            List<BillExchangeInfo> bills= infoService.checkBillNo(invoicenumber);
            BillExchangeInfo billExchangeInfo = infoService.queryById(id);
            String no = "";
            if(id!=-1){
                no=  billExchangeInfo.getInvoiceNo();//原有报关单号
            }
            if(bills.size()>0){
                re="wrong";
            }
            if(invoicenumber.equals(no)){
                re="success";
            }
        }catch (Exception e){
            re="wrong";
        }
        return R.build(re);
    }


    /**
     * 根据发票号码获取结汇信息
     * @param invoiceNumber
     * @return
     */
    @GetMapping("/findBillExchangeInfo")
    @ResponseBody
    public R findBillExchangeInfo(String invoiceNumber){
        try{
            List<BillExchangeInfo> bills= infoService.checkBillNo(invoiceNumber);
            if (!CollectionUtils.isEmpty(bills)){
               return R.build(bills.get(0));
            }else {
                return R.build(ResultStatusEnum.DATA_ERROR);
            }
        }catch (Exception e){}
        return R.build(ResultStatusEnum.DATA_ERROR);
    }

    /**
     * 根据发票号码获取收款情况
     * @param invoiceNumber
     * @return
     */
    @GetMapping("/findReceive")
    @ResponseBody
    public R<String> findReceive(String invoiceNumber){
        String re="";
        try{
            ReceivePaymentDetailEntity findD=new ReceivePaymentDetailEntity();
            findD.setInvoiceNumber(invoiceNumber);
            findD.setValid(DataIsValidEnum.VALID.getId());
            List<ReceivePaymentDetailEntity> receivePaymentDetailEntities = receivePaymentDetailService.queryAll(findD);
            ReceivePaymentSplitEntity findS=new ReceivePaymentSplitEntity();
            findS.setInvoiceNumber(invoiceNumber);
            findS.setValid(DataIsValidEnum.VALID.getId());
            List<ReceivePaymentSplitEntity> receivePaymentSplitEntities = receivePaymentSplitService.queryAll(findS);
            if(receivePaymentDetailEntities.size()>0){
                re="该结汇已关联收款认领，或者拆分，如需操作，请退回删除关联收款单据";
            }
            if(receivePaymentSplitEntities.size()>0){
                re="该结汇已关联收款认领，或者拆分，如需操作，请退回删除关联收款单据";
            }
        }catch (Exception e){}
        return R.build(re);
    }

    /**
     * 根据结汇id批量修改状态
     * @return
     */
    @GetMapping("/checkAllStatus")
    @ResponseBody
    public R<String> checkAllStatus(String id,String type){
        String re="success";
       try{
        ArrayList<Integer> ids=new ArrayList<>();
        String[] split = id.split(",");
        for(String s:split){
            ids.add(Integer.parseInt(s));
        }
        if(type.equals("完成")){
            for(Integer i:ids){
                BillExchangeInfo bill=new BillExchangeInfo();
                bill.setBillId(i);
                bill.setStatus(4);
                infoService.update(bill);
            }
        }else if(type.equals("已批")){
            for(Integer i:ids){
                BillExchangeInfo bill=new BillExchangeInfo();
                bill.setBillId(i);
                bill.setStatus(3);
                infoService.update(bill);
            }
        }}catch (Exception e){
           re="wrong";
       }
        return R.build(re);
    }

    /*
     * 查询公司的logo和img
     * */
    //获取对应所有附件
    @GetMapping("/selectLogo")
    @ResponseBody
    public R<logo> selectLogo(Integer declare_id){
        logo logo=new logo();
        try {
            com.erp.erp_entitys.bill_declare.logo logo1 = infoService.selectLogo(declare_id);
            if(logo1.getChinaLogo()!=null){
                ftpService.ftpUpload(logo1.getChinaLogo());
            }
            if(logo1.getEnginshLogo()!=null){
                ftpService.ftpUpload(logo1.getEnginshLogo());
            }
            if(logo1.getSimg()!=null){
                ftpService.ftpUpload(logo1.getSimg());
            }

        }catch (Exception e){
            System.out.println(e);
        }
        return R.build(logo);
    }
    /**
     * 结汇费用统计导出Excel
     *
     * @return 统计信息1
     */
    @GetMapping(value = "/getCostContractStatisticsOneInfo")
    @ResponseBody
    public R getCostContractStatisticsOneInfo(InfoSearch search) {
        try {
            LOGGER.info("结汇-费用-统计-导出Excel");
            search=getSearch(search);
            JSONObject obj = infoService.getCostContractStatisticsOneInfo(search);
            return R.build(obj);
        } catch (Exception e) {
            LOGGER.info("结汇-费用-统计-导出Excel异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 结汇统计导出Excel
     *
     * @return 统计信息1
     */
    @GetMapping(value = "/getProductContractStatisticsOneInfo")
    @ResponseBody
    public R getProductContractStatisticsOneInfo(InfoSearch search) {
        try {
            LOGGER.info("结汇-产品-统计-导出Excel");
            search=getSearch(search);
            JSONObject obj = infoService.getProductContractStatisticsOneInfo(search);
            return R.build(obj);
        } catch (Exception e) {
            LOGGER.info("结汇-产品-统计-导出Excel异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

   public InfoSearch getSearch(InfoSearch search){
       if(search.getStatus()==null&&search.getSalesman_code()==null&&search.getOp_code()==null&&search.getInvoiceStar()==null&&search.getInvoiceEnd()==null&&search.getCompany_code()==null&&search.getCarryStar()==null&&search.getCarryEnd()==null&&search.getBill()==null){
           search.setStatus(-1);
       }
       search = ChangeUnit.getSearch(search);
       if(search.getBoxStatus()!=null){
           String[] split = search.getBoxStatus().split(",");
           List arr=new ArrayList();
           for(String s:split){
               arr.add(Integer.parseInt(s));
           }
           search.setBoxStatuss(arr);
       }
       if(search.getBusiness_mode()!=null){
           String[] split = search.getBusiness_mode().split(",");
           List arr=new ArrayList();
           for(String s:split){
               if(s!=""&&s!=null){
                   arr.add(s);
               }
           }
           if(arr.size()>0){
               search.setBusiness_modes(arr);
           }else{
               search.setBusiness_modes(null);
           }

       }
       return search;
   }

    /**
     *
     * 判断该用户是否拥有 结汇产品及配件字段显示(JHCPJPJZDXS001) 角色
     */
    @RequestMapping("isContainsRole")
    @ResponseBody
    public R isContainsRole(){
        try {
            LOGGER.info("结汇-判断该用户是否拥有 结汇产品及配件字段显示(JHCPJPJZDXS001) 角色");
            UserEntity user = (UserEntity) this.getBean("user");
            if (user.getRoles().contains("JHCPJPJZDXS001")){
                return R.build(true);
            }else {
                return R.build(false);
            }
        } catch (Exception e) {
            LOGGER.info("结汇-判断该用户是否拥有 结汇产品及配件字段显示(JHCPJPJZDXS001) 角色 异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }

    /**
     * 根据主id获取产品中的外销合同号
     * 返回外销合同号集合
     */
    @RequestMapping("getContractNo")
    @ResponseBody
    public R getContractNo(Integer id){
        try {
            if (id==null){
                return R.build(null);
            }
            //查询到的产品信息
            BillExchangeProductInfo pro=new BillExchangeProductInfo();
            pro.setBillId(id);
            List<BillExchangeProductInfo> productInfos = productService.queryAll(pro);
            List<String> saleContractNoCollect = productInfos.stream().map(p -> p.getSaleContractNo()).collect(Collectors.toList());
            List<String> saleContractNoDistinct = saleContractNoCollect.stream().distinct().collect(Collectors.toList());
            return R.build(saleContractNoDistinct);
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }

    /**
     * 判断该用户是否含有营销总监，财务，管理员角色
     */
    @RequestMapping("isUerRoles")
    @ResponseBody
    public R isUerRoles(){
        try {
            LOGGER.info("结汇-判断该用户是否含有总监，财务，管理员角色");
            UserEntity user = (UserEntity) this.getBean("user");
            if (user.getRoles().contains("YXZJ003")){
                return R.build(true);
            }else if (user.getRoles().contains("CW01")){
                return R.build(true);
            }else if (user.getRoles().contains("admin")){
                return R.build(true);
            }else {
                return R.build(false);
            }
        } catch (Exception e) {
            LOGGER.info("结汇-判断该用户是否含有营销总监，财务，管理员角色 异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }

}